#include <stdio.h>
#include <stdlib.h>

#include "libs.h"

static struct file_link list_head;

const char kindle_previewer[] = "https://www.amazon.com/gp/feature.html?docId=1000765261";
const char mac_link_cmd[] = 
	"ln -s /Applications/Kindle\\ Previewer\\ 3.app/Contents/lib/fc/bin/kindlegen \
/usr/local/bin/kindlegen";

void printf_info(void)
{
	printf("convert txt file to mobi format\n");
	printf("mac: please download \"Kindle Previewer\" from \n %s\n", kindle_previewer);
	printf("mac: specified the kindlegen path\n");
	//printf("  windows: Kindle Previewer install dir \n \
	//	\\lib\\fc\\bin\\kindlegen.exe \n");
	printf("  mac: \n%s\n", mac_link_cmd);
	printf("app tested under kindlegen V2.9\n");

	printf("\n\n");
	printf("please ensure txt file is UTF-8 charset\n");
	printf("start to convert \n");
}

long get_file_size(FILE* fp)
{
	long size;
	fseek(fp, 0, SEEK_END);
	size = ftell(fp);
	//restore file pointer
	fseek(fp, 0, SEEK_SET);

	return size;
}

/*
	convert 

middle files:
	toc: book-toc.html, toc.ncx
	cover: cover.html
	style: style.css
	opf: content.opf
chapter files:
chapter1.html chapter3.html chapter5.html ...

output mobi:
	kindlegen content.opf
*/
void txt2mobi(char *buf, long size, char* title)
{
	int ret = 0;
	init_list(&list_head, size);
	ret = build_toc(buf, size, &list_head);
	if (ret) {
		destroy_list(&list_head);
		return;
	}
	//book-toc.html, toc.ncx
	output_book_toc(buf, title, &list_head);
	output_cover(buf, title);
	output_ncx(buf, title, &list_head);
	output_opf(buf, title, &list_head);
	output_html(buf, title, &list_head);

	destroy_list(&list_head);
	output_mobi(title);
}

//usage: mobi_convert file_name.txt
int main(int argc, char** argv)
{
	FILE* fp = NULL;
	long size = 0;
	char* buf = NULL;
	char title[MAX_CHAPTER_NAME_LEN];
//print help info
	printf_info();
	if (argc < 2) {
		printf("please specified the txt file name\n");
		return -1;
	}

//open txt file and read to buf
	fp = fopen(argv[1], "r");
	if (!fp) {
		printf("can't open file %s\n", argv[1]);
		return -1;
	}
	parse_title_name(argv[1], title);
	set_novel_name(title);
	size = get_file_size(fp);
	printf("txt file %s len is %ld bytes\n", argv[1], size);

	buf = malloc(size + 1);
	if (!buf)
		goto exit;
	size = (long)fread(buf, 1, size, fp);
	buf[size] = 0;
	fclose(fp);
	fp = NULL;

	//main process
	txt2mobi(buf, size, title);
	printf("\nfinished converting mobi\n");

exit:
	if (buf)
		free(buf);
	if (fp)
		fclose(fp);
	return 0;
}
